import { defineStore } from "pinia";
import { persistedstateConfig } from "@/stores/persistedstate";
import type { UserState } from "@/stores/interface";
import { getShowMenuList, getFlatMenuList, filterMenuList } from "@/utils";
import { getUserMenuListApi } from "@/api/user";

const useUserStore = defineStore("user", {
  state: (): UserState => ({
    token: "",
    menuList: [], // 菜单
    rulesName: [], //权限
    userInfo: {},
    tagsList: [{ path: "/home/index", title: "首页" }], // 顶部标签页
    isExpand: true // 菜单横向是否展开
  }),
  getters: {
    // 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuList: (state) => getShowMenuList(state.menuList),
    // 扁平化之后的一维数组菜单，用来添加动态路由
    flatMenuList: (state) => getFlatMenuList(state.menuList)
  },
  actions: {
    // 退出登录
    resetUserInfo() {
      this.tagsList = [{ path: "/home/index", title: "首页" }];
      this.token = "";
      this.menuList = [];
      this.rulesName = [];
      this.userInfo = {};
    },

    // 菜单横向是否展开
    changeIsExpand() {
      this.isExpand = !this.isExpand;
    },

    // 获取菜单列表
    async getMenuList() {
      const res = await getUserMenuListApi();
      const result = filterMenuList((res as any).menuList);
      this.menuList = result;
      this.rulesName = (res as any).permissionList;
    },
    // 设置 tabs
    setTagsList(tagsList: { path: string; title: string }[]) {
      this.tagsList = tagsList;
    }
  },
  persist: persistedstateConfig("user", ["token", "userInfo", "tagsList"])
});
export default useUserStore;
